from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import and_, or_, func, select

from app.core.database import get_db
from app.models.user import User
from app.schemas.user import UserResponse, UserUpdate, UserProfile
from app.api.v1.endpoints.auth import get_current_active_user

router = APIRouter()


@router.get("/me", response_model=UserResponse)
async def get_current_user_profile(
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    return current_user


@router.put("/me", response_model=UserResponse)
async def update_current_user(
    user_update: UserUpdate,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """更新当前用户信息"""
    # 检查用户名是否已存在（如果要更新用户名）
    if user_update.username and user_update.username != current_user.username:
        result = await db.execute(
            select(User).where(
                and_(
                    User.username == user_update.username,
                    User.id != current_user.id
                )
            )
        )
        existing_user = result.scalar_one_or_none()
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Username already exists"
            )
    
    # 检查邮箱是否已存在（如果要更新邮箱）
    if user_update.email and user_update.email != current_user.email:
        result = await db.execute(
            select(User).where(
                and_(
                    User.email == user_update.email,
                    User.id != current_user.id
                )
            )
        )
        existing_user = result.scalar_one_or_none()
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Email already exists"
            )
    
    # 更新用户信息
    update_data = user_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(current_user, field, value)
    
    await db.commit()
    await db.refresh(current_user)
    return current_user


@router.get("/profile/{user_id}", response_model=UserProfile)
async def get_user_profile(
    user_id: int,
    db: AsyncSession = Depends(get_db)
):
    """获取指定用户的公开信息"""
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    
    return user


@router.get("/search", response_model=List[UserProfile])
async def search_users(
    q: Optional[str] = Query(None, description="搜索关键词"),
    skills: Optional[List[str]] = Query(None, description="技能筛选"),
    location: Optional[str] = Query(None, description="位置筛选"),
    min_reputation: Optional[int] = Query(None, description="最小声誉分"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db)
):
    """搜索用户"""
    query = select(User).where(User.is_active == True)
    
    # 关键词搜索
    if q:
        search_filter = or_(
            User.username.ilike(f"%{q}%"),
            User.full_name.ilike(f"%{q}%"),
            User.bio.ilike(f"%{q}%")
        )
        query = query.where(search_filter)
    
    # 技能筛选
    if skills:
        for skill in skills:
            query = query.where(User.skills.contains([skill]))
    
    # 位置筛选
    if location:
        query = query.where(User.location.ilike(f"%{location}%"))
    
    # 声誉分筛选
    if min_reputation is not None:
        query = query.where(User.reputation_score >= min_reputation)
    
    # 按声誉分排序
    query = query.order_by(User.reputation_score.desc())
    
    # 分页
    offset = (page - 1) * size
    query = query.offset(offset).limit(size)
    
    result = await db.execute(query)
    users = result.scalars().all()
    
    return users


@router.get("/leaderboard", response_model=List[UserProfile])
async def get_user_leaderboard(
    type: str = Query("reputation", description="排行榜类型: reputation, competitions, projects"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db)
):
    """获取用户排行榜"""
    query = select(User).where(User.is_active == True)
    
    # 根据类型排序
    if type == "reputation":
        query = query.order_by(User.reputation_score.desc())
    elif type == "competitions":
        query = query.order_by(User.competitions_participated.desc())
    elif type == "projects":
        query = query.order_by(User.projects_created.desc())
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid leaderboard type"
        )
    
    # 分页
    offset = (page - 1) * size
    query = query.offset(offset).limit(size)
    
    result = await db.execute(query)
    users = result.scalars().all()
    
    return users


@router.get("/stats")
async def get_user_stats(
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """获取当前用户统计数据"""
    # 这里可以添加更详细的统计查询
    # 比如最近参与的竞赛、项目进展等
    
    stats = {
        "competitions_participated": current_user.competitions_participated,
        "projects_created": current_user.projects_created,
        "teams_joined": current_user.teams_joined,
        "reputation_score": current_user.reputation_score,
        "profile_completion": calculate_profile_completion(current_user),
        "recent_activities": []  # 可以添加最近活动
    }
    
    return stats


def calculate_profile_completion(user: User) -> float:
    """计算用户资料完成度"""
    total_fields = 10
    completed_fields = 0
    
    if user.full_name:
        completed_fields += 1
    if user.avatar_url:
        completed_fields += 1
    if user.bio:
        completed_fields += 1
    if user.location:
        completed_fields += 1
    if user.website:
        completed_fields += 1
    if user.skills:
        completed_fields += 1
    if user.interests:
        completed_fields += 1
    if user.is_verified:
        completed_fields += 1
    
    # 基础字段（用户名、邮箱）
    completed_fields += 2
    
    return (completed_fields / total_fields) * 100